package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDto;
import com.heima.model.admin.dtos.AdUserLoginResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-12-22
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    private static final Integer TOKEN_EXPIRE_MINUTES = 120;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public AdUserLoginResultDto login(AdUserLoginDto dto) {
        // 根据name查询是否存在
        AdUser user = selectByUserName(dto.getName());
        if(user == null){
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        // 如果存在，判断密码是否匹配
        String passwordDB = user.getPassword();
        String passwordInput = dto.getPassword();
        boolean matches = passwordEncoder.matches(passwordInput, passwordDB);
        if(!matches){
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 生成jwt token返回
        String token = JwtUtils.generateTokenExpireInMinutes(user.getId(), TOKEN_EXPIRE_MINUTES);
        // 返回
        return new AdUserLoginResultDto(BeanHelper.copyProperties(user, AdUserDto.class),token);
    }


    private AdUser selectByUserName(String name){
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AdUser::getName, name);
        return this.getOne(queryWrapper);
    }

}
